﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using System.Threading;

namespace YunxSoft.Abp.LanguageManagement.EntityFrameworkCore;

public class EfCoreLanguageRepository : EfCoreRepository<ILanguageManagementDbContext, Language, Guid>, ILanguageRepository
{    
    public EfCoreLanguageRepository(IDbContextProvider<ILanguageManagementDbContext> dbContextProvider)
        : base(dbContextProvider)
    {
    }

    public virtual async Task<List<Language>> GetListAsync(bool isEnabled)
    {
        return await DbSet.Where(p => p.IsEnabled == isEnabled).ToListAsync();
    }

    public async Task<long> GetCountAsync(string? filter = null, CancellationToken cancellationToken = default)
    {
        var languages = await (await GetFilteredQueryableAsync(filter))
            .CountAsync(cancellationToken);
        return languages;
    }

    public async Task<List<Language>> GetListAsync(string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0, string? filter = null, CancellationToken cancellationToken = default)
    {
        var languages = await (await GetFilteredQueryableAsync(filter))
            .OrderBy(sorting ?? "CreationTime desc")
            .PageBy(skipCount, maxResultCount)
            .ToListAsync(cancellationToken);
        return languages;
    }
    
      protected virtual async Task<IQueryable<Language>> GetFilteredQueryableAsync(string? filter = null)
      {
          var query = await GetQueryableAsync();

        return query
            .WhereIf(!filter.IsNullOrWhiteSpace(), x => x.CultureName.Contains(filter))
            .WhereIf(!filter.IsNullOrWhiteSpace(), x => x.UiCultureName.Contains(filter))
            .WhereIf(!filter.IsNullOrWhiteSpace(), x => x.DisplayName.Contains(filter));
    }
}